package kr.hkit.androidcomplete02.ch19;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class LooperEx extends Activity {
	TextView mMainTv;
	TextView mBackTv;
	EditText mEdit;
	int mainValue;
	CalcThread thread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_loopertest);
		mMainTv = (TextView) findViewById(R.id.looper_mainvalue);
		mBackTv = (TextView) findViewById(R.id.looper_backvalue);
		mEdit = (EditText) findViewById(R.id.looper_number);
		
		thread = new CalcThread(mMainHandler);
		thread.setDaemon(true);
		thread.start();
	}
	
	public void mOnClick(View v){
		Message msg = null;
		switch(v.getId()){
		case R.id.looper_increase:
			mainValue++;
			mMainTv.setText("Main Value : " + mainValue);
			break;
		case R.id.looper_square:
			msg = Message.obtain(thread.mBackHandler, 0, Integer.parseInt(mEdit.getText().toString()), 0);
			thread.mBackHandler.sendMessage(msg);
			break;
		case R.id.looper_root:
			msg = Message.obtain(thread.mBackHandler, 1, Integer.parseInt(mEdit.getText().toString()), 0);
			thread.mBackHandler.sendMessage(msg);
			break;
		}
		
	}
	
	Handler mMainHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0://제곱
				mBackTv.setText("Square Result : " + msg.arg1);
				break;

			case 1://제곱근
				mBackTv.setText("Root Result : " + ((Double)msg.obj).doubleValue());
				break;
			}
		};
	};
}

class CalcThread extends Thread{
	Handler mMainHandler;
	Handler mBackHandler;
	
	public CalcThread(Handler mMainHandler) {
		this.mMainHandler = mMainHandler;
	}
	
	@Override
	public void run() {
		Looper.prepare();
		 
		mBackHandler = new Handler(){
			public void handleMessage(Message msg) {
				Message retMsg = null; 
				switch(msg.what){
				case 0:	//square
					retMsg  = Message.obtain(mMainHandler, 0, msg.arg1 * msg.arg1, 0);
					break;
				case 1://root
					retMsg  = Message.obtain(mMainHandler, 1, new Double(Math.sqrt(msg.arg1)));
					break;
				}
				mMainHandler.sendMessage(retMsg);
			}
		};
		
		Looper.loop();
	}
	
}





